package coreUtils

import (
	"bytes"
	"encoding/base64"
	"errors"
	"image"
	"image/jpeg"
	"strings"

	"github.com/nfnt/resize"
)

// ResizeByBase64 压缩图片(原始图片数据是base64)
func ResizeByBase64(base64Str string, percent int) (string, error) {
	if percent <= 0 || percent >= 100 {
		return "", errors.New("压缩比例不正确")
	}
	if idx := strings.Index(base64Str, ","); idx != -1 {
		base64Str = base64Str[idx+1:]
	}
	// 1. Base64 解码
	imgData, err := base64.StdEncoding.DecodeString(base64Str)
	if err != nil {
		return "", err
	}

	// 2. 解码图片
	img, _, err := image.Decode(bytes.NewReader(imgData))
	if err != nil {
		return "", err
	}
	width := img.Bounds().Dx()
	height := img.Bounds().Dy()

	// 4. 压缩/缩放，使用 nfnt/resize
	newWidth := uint(float64(percent*width) / 100)   // 按比例缩小
	newHeight := uint(float64(percent*height) / 100) // 按比例缩小
	resizedImg := resize.Resize(newWidth, newHeight, img, resize.Lanczos3)

	// 6. 将压缩后的图像编码回 JPEG 缓冲区（用于Base64）
	var buf bytes.Buffer
	if err = jpeg.Encode(&buf, resizedImg, &jpeg.Options{Quality: 80}); err != nil {
		return "", err
	}

	// 7. 编码回 Base64
	compressedBase64 := base64.StdEncoding.EncodeToString(buf.Bytes())

	return compressedBase64, nil
}
